package com.lagou.client.config;

import com.lagou.client.handler.UserClientHandler;
import com.lagou.pojo.RpcRequest;
import com.lagou.util.JSONSerializer;
import com.lagou.util.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //声明一个自定义事件处理器  UserClientHandler
    private static UserClientHandler userClientHandler;

    //1.创建一个代理对象
    public Object createProxy(final Class<?> serviceClass, final String className,final String methodName){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //1）调用初始化netty客户端的方法
                if(userClientHandler == null){
                 initClient();
                }
                // 设置参数
                RpcRequest req = new RpcRequest();
                //className必须与服务端中的实现类在ioc容器内的名称完全一致，否则会找不到实现类对象
                req.setClassName(className);
                //使用灵活判断途径时，方法名和方法传参类型列表都必须完全一致
                req.setMethodName(methodName);
                Class<?>[] clazz = {String.class};
                req.setParameterTypes(clazz);
                //2)实际传参
                req.setParameters(args);
                //userClientHandler.setPara(providerName+args[0]);
                userClientHandler.setPara(req);
                //3).使用线程池,开启一个线程处理处理call() 写操作,并返回结果
                Object result = executor.submit(userClientHandler).get();

                //4)return 结果
                return result;
            }
        });
    }


    //2.初始化netty客户端
    public static  void initClient() throws InterruptedException {
        //1) 初始化UserClientHandler
        userClientHandler = new UserClientHandler();
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        //5)连接服务端
        bootstrap.connect("127.0.0.1",8990).sync();

    }


}
